package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.entity.Department;
import com.example.smartmedicalsystem.entity.Doctor;
import com.example.smartmedicalsystem.entity.Schedule;
import com.example.smartmedicalsystem.entity.User;
import com.example.smartmedicalsystem.repository.DepartmentRepository;
import com.example.smartmedicalsystem.repository.DoctorRepository;
import com.example.smartmedicalsystem.repository.ScheduleRepository;
import com.example.smartmedicalsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final UserRepository userRepository;
    private final DoctorRepository doctorRepository;
    private final DepartmentRepository departmentRepository;
    private final ScheduleRepository scheduleRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 获取所有科室列表
     */
    @GetMapping("/departments")
    @ResponseBody
    public ResponseEntity<List<Department>> getAllDepartments() {
        List<Department> departments = departmentRepository.findAll();
        return ResponseEntity.ok(departments);
    }

    @GetMapping("/doctors")
    public List<Doctor> getAllDoctors() {
        return doctorRepository.findAll();
    }

    @GetMapping("/schedules/{doctorId}")
    public List<Schedule> getSchedulesByDoctor(@PathVariable Long doctorId) {
        Doctor doctor = doctorRepository.findById(doctorId)
                .orElseThrow(() -> new RuntimeException("医生不存在"));
        return scheduleRepository.findByDoctor(doctor);
    }


    /**
     * 根据科室ID获取医生列表
     */
    @GetMapping("/doctors/byDepartment")
    public ResponseEntity<?> getDoctorsByDepartment(@RequestParam Long departmentId) {
        Optional<Department> deptOpt = departmentRepository.findById(departmentId);
        if (!deptOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("科室不存在");
        }
        List<Doctor> doctors = doctorRepository.findByDepartment(deptOpt.get());
        return ResponseEntity.ok(doctors);
    }

    /**
     * 新增医生（由管理员创建医生时使用）
     * 前端传入医生对象，包含：
     *  - user: { username, password }
     *  - name, specialty
     *  - department: { id }
     */
    @PostMapping("/doctors")
    public ResponseEntity<?> addDoctor(@RequestBody Doctor doctor) {
        if (userRepository.findByUsername(doctor.getUser().getUsername()) != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在");
        }
        // 创建用户，设置角色为 DOCTOR，并加密密码
        User user = doctor.getUser();
        user.setRole(User.Role.DOCTOR);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        User savedUser = userRepository.save(user);
        doctor.setUser(savedUser);
        // 如果前端传入了科室ID，则加载并设置科室
        if (doctor.getDepartment() != null && doctor.getDepartment().getId() != null) {
            Optional<Department> deptOpt = departmentRepository.findById(doctor.getDepartment().getId());
            deptOpt.ifPresent(doctor::setDepartment);
        }
        Doctor savedDoctor = doctorRepository.save(doctor);
        return ResponseEntity.ok(savedDoctor);
    }

    /**
     * 创建排班
     * 前端传入 JSON 数据，包含：
     *   dayOfWeek: (如 "MON")
     *   timeSlot: (如 "08:00-10:00")
     *   doctor: { id: 医生ID } —— 此处医生由前端下拉选择，显示医生姓名
     */
    @PostMapping("/schedules")
    public ResponseEntity<?> createSchedule(@RequestBody Schedule schedule) {

        Doctor doctor = doctorRepository.findById(schedule.getDoctor().getId())
                .orElseThrow(() -> new RuntimeException("医生不存在"));

        schedule.setDoctor(doctor);

        scheduleRepository.save(schedule);
        return ResponseEntity.ok("排班创建成功");
    }

    /**
     * 获取所有排班记录
     */
    @GetMapping("/schedules")
    public ResponseEntity<List<Schedule>> getAllSchedules() {
        List<Schedule> schedules = scheduleRepository.findAll();
        return ResponseEntity.ok(schedules);
    }

}
